<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Concurrent</title>
</head>

<body>
  <script>
    function delay(delay) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(delay);
        }, delay);
      })
    }
    let tasks = [
      () => {
        return delay(1000)
      },
      () => {
        return delay(1003)
      },
      () => {
        return delay(1005)
      },
      () => {
        return delay(1002)
      },
      () => {
        return delay(1004)
      },
      () => {
        return delay(1006)
      },
    ]

    function createRequest(tasks, limit, callback) {
      if (typeof limit === 'function') {
        callback = limit;
        limit = 3;
      }
      if (typeof limit !== 'number') limit = 3;
      if (typeof callback !== 'function') callback = function () {}

      class TaskQueue {
        constructor() {
          this.index = 0;
          this.queue = [];
          this.results = [];
        }
        pushTask(task) {
          this.queue.push(task);
          this.next();
        }
        next() {
          while (this.index < limit && this.queue.length) {
            this.index++;
            const task = this.queue.shift();
            task().then(res => {
              this.results.push(res);
              this.next();
            }).finally(error => {
              this.index--;
              this.next();
            })
          }
          if (this.index === 0) callback(this.results);
        }
      }
      const taskQueue = new TaskQueue;
      tasks.map(task => taskQueue.pushTask(task))
    }
    createRequest(tasks, 3, res => console.log(res))
  </script>
</body>

</html>